<template>
  <el-select
    v-model="selectedValue"
    :placeholder="placeholder"
    :style="{ width: width }"
    :clearable="clearable"
    :filterable="filterable"
    :remote="remote"
    :remote-method="handleRemoteSearch"
    :loading="loading"
    :disabled="disabled"
    @change="handleChange"
    @clear="handleClear"
    @focus="handleFocus"
  >
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.label"
      :value="item.id"
    >
      <div class="house-option">
        <span v-html="highlightKeyword(item.label, searchKeyword)"></span>
        <span v-if="item.address" class="house-address" v-html="highlightKeyword(item.address, searchKeyword)"></span>
      </div>
    </el-option>
  </el-select>
</template>

<script setup name="HouseSelector">
import { getHouseList } from "@/api/fang/common"
import { getHomeownersContract } from "@/api/fang/homeowners"

// 定义组件属性
const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: null
  },
  placeholder: {
    type: String,
    default: "请选择房源"
  },
  width: {
    type: String,
    default: "100%"
  },
  clearable: {
    type: Boolean,
    default: true
  },
  filterable: {
    type: Boolean,
    default: true
  },
  remote: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  minSearchLength: {
    type: Number,
    default: 1
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change', 'clear'])

// 响应式数据
const selectedValue = ref(props.modelValue)
const options = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 监听外部值变化
watch(() => props.modelValue, (newVal, oldVal) => {
  selectedValue.value = newVal
  // 如果值变化且新值存在，但 options 中没有该选项，则加载详情
  if (newVal && newVal !== oldVal && !options.value.find(item => item.id === newVal)) {
    loadHouseDetail(newVal)
  }
})

// 加载房源详情（用于初始化时显示已有选中项的地址）
async function loadHouseDetail(contractId) {
  if (!contractId) return
  
  // 检查是否已经加载过
  if (options.value.find(item => item.id === contractId)) {
    return
  }
  
  try {
    loading.value = true
    const response = await getHomeownersContract(contractId)
    const data = response.data || {}
    
    // 构建选项对象，格式与 getHouseList 返回的一致
    const houseOption = {
      id: contractId,
      label: data.address || `房源ID: ${contractId}`, // 使用地址作为显示文本
      address: data.address || '',
      houseArea: data.houseArea || '',
      houseType: data.houseType || data.houseTypeDescription || ''
    }
    
    // 添加到选项中
    const existingIndex = options.value.findIndex(item => item.id === contractId)
    if (existingIndex === -1) {
      options.value.push(houseOption)
    } else {
      options.value[existingIndex] = houseOption
    }
  } catch (error) {
    console.error('加载房源详情失败:', error)
    // 即使失败也添加一个占位选项，避免显示ID
    const fallbackOption = {
      id: contractId,
      label: `房源ID: ${contractId}`,
      address: ''
    }
    const existingIndex = options.value.findIndex(item => item.id === contractId)
    if (existingIndex === -1) {
      options.value.push(fallbackOption)
    }
  } finally {
    loading.value = false
  }
}

// 组件挂载时，如果已有初始值，加载详情
onMounted(() => {
  if (props.modelValue) {
    loadHouseDetail(props.modelValue)
  }
})

// 监听内部值变化
watch(selectedValue, (newVal) => {
  emit('update:modelValue', newVal)
})

// 远程搜索房源
async function handleRemoteSearch(queryString) {
  searchKeyword.value = queryString
  
  // 检查最小搜索长度
  if (queryString.length < props.minSearchLength) {
    options.value = []
    return
  }
  
  if (queryString !== '') {
    loading.value = true
    try {
      const response = await getHouseList({ searchKey: queryString })
      options.value = response.rows || []
    } catch (error) {
      console.error('搜索房源失败:', error)
      options.value = []
    } finally {
      loading.value = false
    }
  } else {
    options.value = []
  }
}

// 选择变化处理
function handleChange(value) {
  const selectedOption = options.value.find(item => item.id === value)
  emit('change', value, selectedOption)
}

// 清空处理
function handleClear() {
  emit('clear')
}

// 聚焦处理
function handleFocus() {
  // 可以添加聚焦时的逻辑
}

// 关键字高亮函数
function highlightKeyword(text, keyword) {
  if (!keyword || !text) {
    return text
  }
  
  // 创建正则表达式，忽略大小写
  const regex = new RegExp(`(${keyword})`, 'gi')
  
  // 替换匹配的文本，添加高亮样式
  return text.replace(regex, '<span style="color: #409EFF; font-weight: bold;">$1</span>')
}

// 暴露方法给父组件
defineExpose({
  clear: () => {
    selectedValue.value = null
    options.value = []
    searchKeyword.value = ''
  },
  focus: () => {
    // 可以添加聚焦逻辑
  },
  getSelectedOption: () => {
    return options.value.find(item => item.id === selectedValue.value)
  }
})
</script>

<style scoped>
.house-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.house-address {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

/* 高亮样式 */
:deep(.el-select-dropdown__item) {
  padding: 8px 20px;
}

:deep(.el-select-dropdown__item:hover) {
  background-color: #f5f7fa;
}

:deep(.el-select-dropdown__item.selected) {
  background-color: #409eff;
  color: white;
}

:deep(.el-select-dropdown__item.selected .house-address) {
  color: rgba(255, 255, 255, 0.8);
}
</style>
